"""
简化版翻译服务器 - 使用PaddleNLP而不是PaddleHub
尝试避开libsndfile.dll依赖问题
"""

from flask import Flask, request, jsonify
from flask_cors import CORS
import sys
import os
import time
import json

app = Flask(__name__)
CORS(app)

# 全局变量存储模型
translator = None

def load_translator():
    """
    加载翻译模型
    """
    global translator
    
    try:
        print("尝试使用PaddleNLP加载模型...")
        try:
            from paddlenlp.transformers import TransformerModel
            translator = TransformerModel.from_pretrained('transformer-tiny-en-zh')
            print("✓ PaddleNLP模型加载成功")
            return True
        except ImportError:
            print("✗ 导入PaddleNLP失败")
            
            # 尝试安装PaddleNLP
            print("尝试安装PaddleNLP...")
            os.system("pip install paddlenlp")
            
            from paddlenlp.transformers import TransformerModel
            translator = TransformerModel.from_pretrained('transformer-tiny-en-zh')
            print("✓ PaddleNLP模型安装并加载成功")
            return True
    except Exception as e:
        print(f"✗ PaddleNLP加载失败: {e}")
    
    print("⚠ 警告: 模型加载失败，使用模拟翻译模式")
    translator = "mock"
    return False

def translate_text(text):
    """
    执行翻译
    """
    global translator
    
    if translator is None:
        return "模型未加载"
    
    # 模拟翻译模式
    if translator == "mock":
        # 简单的模拟翻译
        mock_dict = {
            "hello": "你好",
            "world": "世界",
            "hello world": "你好世界",
            "good": "好的",
            "morning": "早上",
            "thank you": "谢谢",
            "how are you": "你好吗",
            "what is ai": "什么是人工智能",
            "artificial intelligence": "人工智能",
            "machine learning": "机器学习",
            "deep learning": "深度学习",
            "neural network": "神经网络",
            "natural language processing": "自然语言处理",
            "computer vision": "计算机视觉",
            "data science": "数据科学",
        }
        
        text_lower = text.lower().strip()
        if text_lower in mock_dict:
            return mock_dict[text_lower]
        else:
            return f"[模拟翻译] {text}"
    
    # 使用真实模型翻译
    try:
        if hasattr(translator, 'predict'):
            # PaddleNLP方式
            result = translator.predict([text])
            return result[0] if isinstance(result, list) else result
        elif hasattr(translator, '__call__'):
            # 其他方式
            result = translator(text)
            return result[0]['translation_text'] if isinstance(result, list) else result
        else:
            return "翻译器类型未知"
    except Exception as e:
        return f"翻译出错: {str(e)}"

@app.route('/translate', methods=['POST'])
def translate():
    """
    翻译API端点
    """
    try:
        data = request.json
        text = data.get('text', '')
        
        if not text:
            return jsonify({'error': '文本为空'}), 400
        
        translation = translate_text(text)
        return jsonify({'translation': translation})
    
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/health', methods=['GET'])
def health():
    """
    健康检查端点
    """
    status = "ready" if translator is not None else "loading"
    return jsonify({
        'status': status,
        'model_type': type(translator).__name__ if translator and translator != "mock" else 'mock'
    })

if __name__ == '__main__':
    print("=" * 50)
    print("简化版翻译服务器启动中...")
    print("=" * 50)
    
    # 加载模型
    success = load_translator()
    
    if success:
        print("\n✓ 服务器准备就绪，使用实际翻译模型")
    else:
        print("\n⚠ 服务器以模拟模式运行")
        print("\n要使用实际的transformer-tiny-en-zh模型，需要解决依赖问题：")
        print("1. 下载并安装libsndfile: https://github.com/libsndfile/libsndfile/releases")
        print("2. 将libsndfile.dll复制到Python目录或系统路径")
    
    print("\n服务器地址: http://localhost:5000")
    print("翻译接口: POST http://localhost:5000/translate")
    print("健康检查: GET http://localhost:5000/health")
    print("\n按 Ctrl+C 停止服务器")
    print("=" * 50)
    
    app.run(host='0.0.0.0', port=5000, debug=False)